by 키워드란?

위임 패턴을 구현하여 프로퍼티의 getter/setter 로직을 다른 객체로 위임 혹은 클래스의 인터페이스 구현을 다른 객체에 위임할 때 사용한다.

val lazyValue: String by lazy {
	println("computed!");
	"Hello"
}
  • Property Delegate : by lazy(지연 초기화), by Delegates.observable(값 변경 감지)
  • Implementation Delegate : 인터페이스의 구현을 다른 객체로 위임

Property Delegate

val/var <property name>: <Type> by <expression>

Implementation Delegate

var stateColor by mutableStateOf(Color.Blue)